package org.com.yz.common.util;

import ch.qos.logback.classic.pattern.DateConverter;
import com.opencsv.CSVReader;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.opencsv.bean.HeaderColumnNameTranslateMappingStrategy;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import org.apache.http.entity.ContentType;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * csv文件读写工具类
 *
 * @author wzc
 * @date 2018/12/3
 */
public class CsvUtils {

    private static final Logger logger = LoggerFactory.getLogger("CsvUtils.class");

    /**
     * 解析csv文件并转成bean
     *
     * @param file  csv文件
     * @param clazz 类
     * @param <T>   泛
     * @return 泛型bean集合
     */
    public static <T> List<T> getCsvData(MultipartFile file, Class<T> clazz) {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(file.getInputStream(), "gbk");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>();
        strategy.setType(clazz);

        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(in)
                .withSeparator(',')
                .withQuoteChar('\'')
                .withMappingStrategy(strategy).build();
        return csvToBean.parse();
    }

    /**
     * 解析csv文件并转成bean
     *
     * @param file  csv文件
     * @param clazz 类
     * @param <T>   泛
     * @return 泛型bean集合
     */
    public static <T> List<T> getCsvData(File file, Class<T> clazz,Map<String, String> columnMapping) {

        FileInputStream fileInputStream = null;
        MultipartFile multipartFile = null;
        InputStreamReader in = null;
        try {
            fileInputStream = new FileInputStream(file);
            multipartFile = new MockMultipartFile(file.getName(), file.getName(),
                    ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
            if (multipartFile != null) {
                in = new InputStreamReader(multipartFile.getInputStream(), "gbk");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        HeaderColumnNameTranslateMappingStrategy<T> strategy =
                new HeaderColumnNameTranslateMappingStrategy<T>();
        strategy.setType(clazz);
        if (columnMapping != null){
            strategy.setColumnMapping(columnMapping);
        }
        CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(in)
                .withSeparator(',')
                .withQuoteChar('\t')
                .withQuoteChar('\'')
                .withMappingStrategy(strategy).build();
        return csvToBean.parse();
    }

    /**
     * 支付宝官方对账单
     * @return
     */
    public static Map<String, String> getZFBColumnMapping(){
        Map<String, String> columnMapping = new HashMap<String, String>();
        columnMapping.put("支付宝交易号", "zfbTransNo");
        columnMapping.put("商户订单号", "merchantOrderNo");
        columnMapping.put("业务类型", "tradingStatus");
        columnMapping.put("商品名称","tradeName");
        columnMapping.put("创建时间", "creationTime");
        columnMapping.put("完成时间", "completionTime");
        columnMapping.put("门店编号", "shopNo");
        columnMapping.put("门店名称", "storeName");
        columnMapping.put("操作员", "operator");
        columnMapping.put("终端号", "terminalNo");
        columnMapping.put("对方账户", "counterAccount");
        columnMapping.put("订单金额（元）", "orderAmount");
        columnMapping.put("商家实收（元）", "merchantReceiptAmount");
        columnMapping.put("支付宝红包（元）", "zfbRed");
        columnMapping.put("集分宝（元）", "jfb");
        columnMapping.put("支付宝优惠（元）", "zfbDiscount");
        columnMapping.put("商家优惠（元）", "merchantDiscount");
        columnMapping.put("券核销金额（元）", "qhxje");
        columnMapping.put("券名称", "ticketName");
        columnMapping.put("商家红包消费金额（元）", "sjhbxfje");
        columnMapping.put("卡消费金额（元）", "kxfje");
        columnMapping.put("退款批次号/请求号", "refundNo");
        columnMapping.put("服务费（元）", "serviceCharge");
        columnMapping.put("分润（元）", "benefit");
        columnMapping.put("备注", "remark");
        return columnMapping;
    }

    /**
     * 兴业微信对账单
     * @return
     */
    public static Map<String, String> getWXColumnMapping(){
        Map<String, String> columnMapping = new HashMap<String, String>();
        columnMapping.put("交易时间", "transaction_time");
        columnMapping.put("平台订单号", "platform_order_number");
        columnMapping.put("交易状态", "trading_status");
        columnMapping.put("总金额","total_sum");
        columnMapping.put("企业红包", "business_envelopes");
        columnMapping.put("平台退款单号", "platform_refund_number");
        columnMapping.put("退款金额", "refund_amount");
        columnMapping.put("退款类型", "refund_type");
        columnMapping.put("退款状态", "refund_status");
        return columnMapping;
    }


    /**
     * 微信官方对账单
     * @return
     */
    public static Map<String, String> getWXGFColumnMapping(){
        Map<String, String> columnMapping = new HashMap<String, String>();
        columnMapping.put("交易时间", "transaction_time");
        columnMapping.put("微信订单号", "platform_order_number");
        columnMapping.put("商户订单号", "platform_merchant_no");
        columnMapping.put("交易类型", "pay_type");
        columnMapping.put("交易状态", "trading_status");
        columnMapping.put("订单金额","total_sum");
        columnMapping.put("应结订单金额","payable_sum");
        columnMapping.put("微信退款单号", "platform_refund_number");
        columnMapping.put("商户退款单号", "merchant_refund_no");
        columnMapping.put("退款金额", "refund_amount");
        columnMapping.put("退款类型", "refund_type");
        columnMapping.put("退款状态", "refund_status");
        columnMapping.put("手续费", "service_charge");
        columnMapping.put("费率", "rate");
        return columnMapping;
    }


    /**
     * 转化CSV到新CSV
     *
     * @param path
     */
    public static void toConversionCSV(String path) {
        ArrayList<ArrayList<String>> csvData = CSV2Array(path);
        Array2CSV(csvData, path);
    }

    /**
     * 转化CSV到新CSV
     *
     * @param path
     */
    public static void toConversionCSV(String path,BufferedReader in) {
        ArrayList<ArrayList<String>> csvData = XMLArray(in);
        Array2CSV(csvData, path);
    }

    /**
     * 解析读取CSV
     *
     * @param path
     * @return
     */
    public static ArrayList<ArrayList<String>> CSV2Array(String path) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(path), "GBK"));
            ArrayList<ArrayList<String>> alldata = new ArrayList<ArrayList<String>>();
            String line;
            String[] onerow;
            while ((line = in.readLine()) != null) {
                if (null != line && !line.equals("") && line.indexOf("#") == -1) {
                    //默认分割符为逗号，可以不使用逗号
                    onerow = line.split(",");
                    List<String> onerowlist = Arrays.asList(onerow);
                    ArrayList<String> onerowaArrayList = new ArrayList<String>(onerowlist);
                    alldata.add(onerowaArrayList);
                }
            }
            in.close();
            return alldata;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 解析读取XML
     * @return
     */
    public static ArrayList<ArrayList<String>> XMLArray(BufferedReader in) {
        try {
            ArrayList<ArrayList<String>> alldata = new ArrayList<ArrayList<String>>();
            String line;
            String[] onerow;
            while ((line = in.readLine()) != null) {
                if (null != line && !line.equals("") && line.indexOf("#") == -1) {
                    if (line.indexOf("总交易单数") != -1){
                        break;
                    }
                    //默认分割符为逗号，可以不使用逗号
                    onerow = line.split(",");
                    List<String> onerowlist = Arrays.asList(onerow);
                    ArrayList<String> onerowaArrayList = new ArrayList<String>(onerowlist);
                    alldata.add(onerowaArrayList);
                }
            }
            in.close();
            return alldata;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 导入CSV数据
     *
     * @param data
     * @param path
     */
    public static void Array2CSV(ArrayList<ArrayList<String>> data, String path) {
        try {
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path), "GBK"));
            for (int i = 0; i < data.size(); i++) {
                ArrayList<String> onerow = data.get(i);
                for (int j = 0; j < onerow.size(); j++) {
                    out.write(onerow.get(j));
                    out.write(",");
                }
                out.newLine();
            }
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}